<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Validator;
use App\Model\SkuModel;
use App\Model\ShopGoodModel;
use App\Model\GroupList;
use App\Model\GroupListOrder;
use App\Model\GroupListLog;
use App\Model\GroupListCite;
use App\Model\AdminLogsModel;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

//拼团
class GroupController extends Controller{
    //添加页
    public function add(Request $request){
         //商品名称
         if(request()->sku_id > 0){
            $good = SkuModel::where('id',request()->sku_id)->first();
            
        }else{
            $good = ShopGoodModel::where('id',request()->id)->first();
        }
        $gname = ShopGoodModel::where('id',request()->id)->value('name');
        
        //判断该商品是否已经添加
        $list = GroupList::where('gid',request()->id)->where('sku_id',request()->sku_id)->first();
        if($list){
            $goods['id'] = $list['id'];
            $goods['gid'] = $list['gid'];
            $goods['sku_id'] = $list['sku_id'];
            $goods['charge'] = $list['charge'];
            $goods['nums'] = $list['nums'];
            $goods['shares'] = $list['shares'];
            $goods['start'] = substr($list['start'],0,16);
            $goods['end'] = substr($list['end'],0,16);
            $goods['state'] = $list['state'];
            $goods['sell'] = $list['sell'];
            $goods['is_exit'] = 1;
            
        }else{
            $goods['id'] = 0;
            $goods['gid'] = $request['gid'];
            $goods['sku_id'] = $request['sku_id'];
            $goods['nums'] = 0;
            $goods['shares'] = 0;
            $goods['start'] = date('Y-m-d 00:00:00',strtotime('+1 day'));
            $goods['end'] = date('Y-m-d 23:59:59',strtotime('+2 day'));
            $goods['charge'] = 0;
            $goods['state'] = 1;
            $goods['sell'] = 0;
            $goods['is_exit'] = 2;
        }
        $type = $request->input('typeaa',2);
        return view('admin.group.add',compact('request','gname','goods','good','type'));
    }

    //添加操作
    public function insert(Request $request){
        //商品ID
        $gid = request()->gid;
        $sku_id = request()->sku_id;

        $post = $request->post();
        $validator = Validator::make($post,[
          'sell'=>'required',
          'charge'=>'required',
		  'shares'=>'required',
		  'nums'=>'required',
		  'start'=>'required',
		  'end'=>'required',
        ],[
          'sell.required' => '销售价不能为空',
          'charge.required' => '利润不能为空',
          'shares.required' => '股票不能为空',
		  'nums.required' => '拼团数不能为空',
		  'start.required' => '开始时间不能为空',
		  'end.required' => '结束时间不能为空',
        ]);
        if($validator->fails()){
          return returnJson(0, $validator->errors()->first());
        }
        if(request()->sell <= 0){
            return ['code'=>0,'msg'=>"请输入销售价"];
        }
        if(request()->charge <= 0){
            return ['code'=>0,'msg'=>'请输入利润'];
        }
        if(request()->start >= request()->end){
            return ['code'=>'0','msg'=>'请输入正确的时间区间'];
        }
        if(request()->nums <= 0){
            return ['code'=>0,'msg'=>'请输入拼团数'];
        }

        //事物
        DB::beginTransaction();
        try {
            //判断该商品是否已经添加
            $list = GroupList::where('gid',$gid)->where('sku_id',$sku_id)->first();
            
            //商品信息
            $good_res = ShopGoodModel::where('id',$gid)->first();
            $gname = $good_res['name'];
            $sell_price = $good_res['sell_price'];
            $cost_price = $good_res['cost_price'];
            $picname = 'http://'.$_SERVER['HTTP_HOST'].$good_res['picpath'].$good_res['picname'];
            $attr = '';
            if($good_res['oss_pic']){
                $picname = $good_res['oss_pic'];
            }
            //规格信息
            if($sku_id){
                $good_sku_res = SkuModel::where('id',$sku_id)->first();
                $sell_price = $good_sku_res['sell_price'];
                $cost_price = $good_sku_res['cost_price'];
                $picname = 'http://'.$_SERVER['HTTP_HOST'].$good_sku_res['picname'];
                if($good_sku_res['oss_pic']){
                    $picname = $good_sku_res['oss_pic'];
                }
                $attr = $good_sku_res['attr'];
            }
            if(request()->end <= date('Y-m-d H:i:s') || request()->start >= request()->end){
                return ['code'=>'0','msg'=>"请确认开始时间和结束时间的区间"];
            }
            if($list){
                GroupList::where('gid',$gid)->where('sku_id',$sku_id)->update([
                    'sell' => request()->sell,
                    'charge' => request()->charge,
                    'nums' => request()->nums,
                    'shares' => request()->shares,
                    'start' => request()->start,
                    'end' => request()->end,
                ]);
            }else{
                
                GroupList::insert([
                    'sell' => request()->sell,
                    'charge' => request()->charge,
                    'nums' => request()->nums,
                    'shares' => request()->shares,
                    'start' => request()->start,
                    'end' => request()->end,
                    'gid' => request()->gid,
                    'sku_id' => request()->sku_id,
                    'state' => 1,
                    'cost' => $cost_price,
                    'picname' => $picname,
                    'attr' => $attr,
                    'name' => $gname,
                ]);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw $e;
            return ['code'=>0,'msg'=>'设置失败'];
        }
        return ['code'=>1,'msg'=>'设置成功'];

    }

    //设置开关
    public function up_state(){
        $id = request()->id;
        $state = request()->state;
        //拼团信息
        $list = GroupList::where('id',$id)->first();
        if(!$list){
            return ['code'=>0,'msg'=>'该拼团商品有误'];
        }
        //事物
        DB::beginTransaction();
        try {
            switch($state){
                //上架
                case '1':
                    if($list['end'] <= date('Y-m-d H:i:s')){
                        return ['code'=>0,'msg'=>'结束时间有误'];
                    }
                    GroupList::where('id',$id)->increment('curcle');
                break;
                //下架
                case '2':
                    $list_log_exit = GroupListLog::where('gid',$list['id'])->where('curcle',$list['curcle'])->first();
                    if($list_log_exit){
                        return ['code'=>0,'msg'=>"该商品正在拼团,不可下架"];
                    }
                break;
            }
            //设置拼团商品开关
            GroupList::where('id',$id)->update(['switch'=>$state]);
            //查询商品信息
            $good = ShopGoodModel::where('id',$list['gid'])->first();
            $state_name = ['1'=>'开启','2'=>'关闭'];
            //添加日志
            $msg = "拼团商品：".$good['name']."(id:".$good['id'].")状态设置为".$state_name[$state];
            AdminLogsModel::addLog($msg);

            DB::commit();
        }catch (Exception $e) {
            DB::rollBack();
            throw $e;
            return ['code'=>0,'msg'=>'设置失败'];
        }
        return ['code'=>1,'msg'=>'设置成功'];
    }

    //拼团列表
    public function index(Request $request){
        $gid = request()->gid;
        $month = request()->month;
        $gname = request()->gname;
        $list = GroupList::when($month, function ($query) use ($month) {
            return $query->where('start','<=', $month)->where('end','>=',$month);
        })
        ->when($gid,function($query) use ($gid){
            return $query->where('gid',$gid);
        })
        ->when($gname,function($query) use ($gname){
            return $query->where('name','like',"%".$gname."%");
        })
        ->orderBy('switch','asc')->orderBy('end','desc')->paginate(15);

        return view('admin.group.index',compact('list','request'));
    }

    //拼团详情
    public function in_team(Request $request){
        $id = request()->id;
        //商品详情
        $list = GroupList::where('id',$id)->first();
        //订单详情
        $order_res = GroupListLog::where('gid',$list['id'])->paginate(15);

        return view('admin.group.inteam',compact('order_res','request'));
    }

    //订单
    public function order(Request $request){
        $list = GroupListLog::where(function ($query) {
			// 状态
			// if (request()->sn) {
			// 	$query->where('gid', request()->gid);
            // }
            if (request()->gname) {
				$query->where('gname', request()->gname);
            }
            if (request()->state) {
				$query->where('status', request()->state);
			}
			// 下单时间
			if (request()->month) {
				$month_arr = explode("~", request()->month);
				$mintime = $month_arr[0];
				$maxtime = $month_arr[1] . " 23:59:59";
				$query->whereBetween('created_at', [$mintime, $maxtime]);
			}
		})->where('state',3)->orderBy('id','desc')->paginate(15);
        return view('admin.group.order',compact('list','request'));
    }

    //历史记录
    public function cite(Request $request){
        $id = request()->id;
        $list = GroupListCite::where('gid',$id)->orderBy('id','desc')->paginate(15);

        return view('admin.group.cite',compact('list','request','id'));
    }

    //参团详情
    public function cite_log(Request $request){
        //商品订单
        $gid = request()->gid;
        //第几轮
        $curcle = request()->curcle;
        $list = GroupListLog::where('gid',$gid)->where('curcle',$curcle)->paginate(15);
        
        return view('admin.group.citelog',compact('list','gid','curcle','request'));


    }

    //发货页面
    public function send_ok(){
        $id = request()->id;
     
        return view('admin.group.sendok',compact('id'));
    }


    //发货
    public function send_ok_cy(){
        $id = request()->id;
        $express_num = request()->express_num;
        $express_com = request()->express_com;

        $list = GroupListLog::where('id',$id)->first();
        if(!$list){
            return ['code'=>0,'msg'=>'该订单信息有误'];
        }

        GroupListLog::where('id',$id)->update(['status'=>2,'express_com'=>$express_com,'express_num'=>$express_num,'send_time'=>date('Y-m-d H:i:s')]);
        return ['code'=>1,'msg'=>"已发货"];
    }
}